package com.self.console.web.listener;

import com.sangame.sow.cache.constant.Constant;
import com.sangame.sow.ssh.spring.SpringBeanManager;
import com.sangame.sow.utils.SshDateUtil;
import com.self.console.config.CommonConfig;
import com.self.console.update.UpdateApplication;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDateModel;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ApplicationListener implements ServletContextListener {

	private static final String LINE_SEP = System.getProperty("line.separator", "\r\n");

	public void contextInitialized(ServletContextEvent evt) {
		// 初始化缓存
		Constant.CONFIG_FILE_PATH = "memcache.properties";
		Constant.DEFAULT_CACHE_PROVIDER = "com.sangame.sow.cache.memcached.MemcachedCacheProvider";

		ServletContext servletContext = evt.getServletContext();
		SpringBeanManager.initContext(WebApplicationContextUtils.getWebApplicationContext(servletContext));

		// 调用升级程序
//		String webPath = evt.getServletContext().getRealPath("/");
//		UpdateApplication updating = UpdateApplication.getInstance();
//		updating.executeUpdate(webPath);

		// freemarker的日期格式统一问题
		Configuration configuration = SpringBeanManager.getBean("freemarkerConfiguration", Configuration.class);
		ObjectWrapper wrapper = configuration.getObjectWrapper();
		if (wrapper instanceof BeansWrapper) {
			((BeansWrapper) wrapper).setDefaultDateType(TemplateDateModel.DATETIME);
		}


		printCopyright();
	}

	public void contextDestroyed(ServletContextEvent evt) {}

	private void printCopyright() {
		CommonConfig config = SpringBeanManager.getBean("commonConfig", CommonConfig.class);
		String print = "-----------------------------------------" + LINE_SEP 
					 + "   P2P Web Application Console" + LINE_SEP
					 + "   Version: " + config.getVersion() + "." + config.getBuildNo() + LINE_SEP 
					 + "   Server Time: " + SshDateUtil.getSecondDateStr(System.currentTimeMillis()) + LINE_SEP
					 + "   Powered by Sangame.com,(C)2006-" + SshDateUtil.getYearStr(System.currentTimeMillis()) + LINE_SEP
					 + "-----------------------------------------" + LINE_SEP;
		System.err.println(print);
	}



}
